<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class RvceoController extends Controller
{
    // 静态获取其下所有代理商ID
    static function AgentId ($agentId)
    {
        $id=array();
        $array_id = DB::table('sa_agent') -> where('path','like','%,'.$agentId.',%') ->select('id') -> get();
        if($array_id)
        {
            foreach ($array_id as $v)
            {
                $id[] = $v['id']; 
            }
        }
        $id[] = $agentId;
        return $id;
    }
    // 主页
    public function index(Request $request)
    {
        //获取登录id
        // $agentId= session('agentId');
        $adminId = $request->cookie('adminId');
        //查询代理商表
        $admin = DB::table('sa_admin as ad')
            -> leftjoin('sa_agent as ag','ag.id','=','ad.agent_id')
            -> select('ad.*','ag.agent_name')
            -> where(['ad.id'=>$adminId])
            -> first();
        return view('admin.rvceo.index',['admin'=>$admin]);
    }
    // 柱状图数据填充
    public function getHistogram(Request $request)
    {
        $where = array();
        $agentId = $request->cookie('agentId');
        $agentId = self::AgentId($agentId);
        $where['lg_genre'] = '自检';
        $data['self_test'] = DB::table('sa_log_msg') -> whereIn('lg_agent_id',$agentId) -> where($where) -> count();
        
        $where['lg_genre'] = '防拆';
        $data['apart'] =  DB::table('sa_log_msg') -> whereIn('lg_agent_id',$agentId) -> where($where) -> count();
        
        $where['lg_genre'] = '火灾';
        $res = DB::table('sa_log_msg') -> whereIn('lg_agent_id',$agentId) -> where($where) -> groupBy('lg_b_name')-> get();
        $data['temper'] = count($res);
        
        $where['lg_genre'] = '欠压';
        $data['voltage'] = DB::table('sa_log_msg') -> whereIn('lg_agent_id',$agentId) -> where($where) -> count();
        
        $where['lg_genre'] = '故障';
        $data['fault'] = DB::table('sa_log_msg') -> whereIn('lg_agent_id',$agentId) -> where($where) -> count();
        // 求数组中最大值 获得key
        $max = array_search(max($data), $data);
        // 求数组中最大值
        // $min = array_search(min($data), $data);
        $max = floor($data[$max]*1.2);
        $data['maxto'] = $max;
        // $data['minto'] = $data[$min];
        echo json_encode($data);
    }
    // ajax 地图数据
    public function getData(Request $request){
        //获取登录id
        $agentId = $request->cookie('agentId');
        $agentId = self::AgentId($agentId);
        // 如果有 ajax传值 判断类型
        if(isset($_GET['Type'])) {
            // 根据第几个标签判断类型
            switch ($_GET['Type']) {
                case 0: // 网关
                    $database = 'sa_base_station';
                    break;
                case 1: // 烟感
                    $database = 'sa_smoke_detector';
                    break;
                case 2: // 红外
                    $database = 'sa_infrared_detector';
                case 3: // 燃气
                    $database = 'sa_gas_detector';
                    break;
                case 4: // 电气
                    $database = 'sa_electric_detector';
                    break;
                case 5: // 呼救
                    $database = 'sa_call_help_detector';
                    break;
                default:
                    $database = false;
            }
            //查询对应数据表
            if($database){
                if($database == 'sa_base_station'){
                    $data = DB::table($database)
                        -> select('bs_eui','bs_name','longitude','latitude')
                        -> whereIn('bs_agent_id',$agentId)
                        -> get();
                }else{
                    $data = DB::table($database)
                        ->LeftJoin('sa_building as b',$database.'.b_id','=','b.b_id')
                        -> select('b.b_longitude as longitude','b.b_latitude as latitude')
                        -> whereIn('agent_id',$agentId)
                        -> get();
                }
                echo json_encode($data);
            }
        }

    }
    public function getWorker(Request $request){
        $agentId = $request->cookie('agentId');
        $agentId = self::AgentId($agentId);
        $Jstr = $_GET['Jstr'];
        //$Jstr = '{"hd":{"ver":"0","rdTk":"1234","pktp":0,"gwad":"T6CN470S0019"},"rxpk":{"time":"2017-05-30T17:54:50.188967Z","tmst":"1496138090","freq":472.700000,"datr":"SF8BW125","rssi":"-96.3","lsnr":"-1.3","chan":6,"mote":{"DevE":"FF00751000000004","DevA":18119,"AppE":"BB02000000AB1111","fcnt":95,"fprt":1,"fmtp":2,"data":"gGQ=","datar":"fa164c483035313431303030303030303030333044100006"}},"action":"app_data"}';
        $info = array();
        $make = false;
        $message = json_decode($Jstr,true);
        $DevE = $message['rxpk']['mote']['DevE'];
        $AppE = $message['rxpk']['mote']['AppE'];
        $str = $message['rxpk']['mote']['datar'];
        //查找绑定位置表
        switch($AppE){
            case 'BB02000000AB1111': // 烟感TBS-100
                // b1 28 00 1e 00 00 e1
                $row = DB::table('sa_smoke_detector') -> where(['eui'=>$DevE]) -> select('agent_id')-> first();
                if(in_array($row['agent_id'],$agentId)){
                    $apply = 'smoke';
                    $sub = substr($str,1,1);
                    $tbs_sub = substr($str,0,2);
                    if($tbs_sub == 'a1'||$tbs_sub == 'b1'){
                        $make = true;
                    }
                    if($sub == 'a'){
                        $make_er = MessageController::haoen($str);
                        if(($make_er['genre']!='恢复')&&($make_er['genre']!='心跳')){
                            $make = true;
                        }
                    }
                    if($tbs_sub == '11'){
                        $gs517_sub =  substr($str,3,1);
                        if($gs517_sub!='7'||$gs517_sub!='A'||$gs517_sub!='B'||$gs517_sub!='C'){
                            $make = true;
                        }
                    }
                }
                break;
            case '0000000000000035': // 电气
                // aa aa 47 00 01 01 00 13 01 44 00 10 00 00 00 00 00 00 00 00 00 00 00 5d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32
                // $data_str = substr($str,22,54);
                // $data_str = substr($str,22,50);
                $row = DB::table('sa_electric_detector') -> where(['eui'=>$DevE]) -> select('agent_id')-> first();
                if(in_array($row['agent_id'],$agentId)){
                    $apply = 'electric';
                    $data_str = substr($str,22,2); // 只查看温度报警
                    $sub = str_replace("0","",$data_str);
                    if(!empty($sub)){
                        $make = true;
                    }
                }
                break;
            case 'BB02000000AB1112': // 呼救
                $row = DB::table('sa_call_help_detector') -> where(['eui'=>$DevE]) -> select('agent_id')-> first();
                if(in_array($row['agent_id'],$agentId)){
                    $apply = 'call_help';
                    if(strlen($str)==10){
                        $make = true;
                    }elseif(strlen($str)==4){
                        $sub = substr($str,0,1);
                        if($sub == '0'){
                            $make = true;
                        }
                    }
                }
                break;
            case '0000000000004912': // 红外
                $row = DB::table('sa_infrared_detector') -> where(['eui'=>$DevE]) -> select('agent_id')-> first();
                if(in_array($row['agent_id'],$agentId)){
                    $apply = 'infrared';
                    $make_er = MessageController::haoen($str);
                    if(($make_er['genre']!='恢复')&&($make_er['genre']!='心跳')){
                        $make = true;
                    }
                }
                break;
            case 'BB02000000AB0001': // 燃气
                $row = DB::table('sa_gas_detector') -> where(['eui'=>$DevE]) -> select('agent_id')-> first();
                if(in_array($row['agent_id'],$agentId)){
                    $apply = 'gas';
                    $make_er = MessageController::haoen($str);
                    if(($make_er['genre']!='恢复')&&($make_er['genre']!='心跳')){
                        $make = true;
                    }
                }
                break;
            default:
                $make = false;
        }
        //判断是否有报警信息
        if($make){
            $smoke_area = DB::table('sa_'.$apply.'_detector as de')
                -> leftJoin('sa_building as bu','de.b_id','=','bu.b_id')
                -> leftJoin('sa_room as rm','de.r_id','=','rm.r_id')
                -> leftJoin('sa_type as tp','tp.id','=','de.type_id')
                -> leftJoin('sa_camera as ca','ca.id','=','de.camera_id')
                -> select('de.r_id','de.b_id','de.a_id','de.status','tp.type','bu.b_name','bu.b_longitude','bu.b_latitude','rm.r_name','rm.r_floor','ca.url')
                -> where('de.eui' ,'=' ,$DevE)
                -> first();
            // $smoke_area = DB::table('sa_'.$apply.'_detector as de')
            //     -> leftJoin('sa_building as bu','de.b_id','=','bu.b_id')
            //     -> leftJoin('sa_room as rm','de.r_id','=','rm.r_id')
            //     -> leftJoin('sa_type as tp','tp.id','=','de.type_id')
            //     -> leftJoin('sa_camera as ca','ca.id','=','de.camera_id')
            //     -> select('de.r_id','de.b_id','de.a_id','tp.type','bu.b_name','bu.b_longitude','bu.b_latitude','rm.r_name','rm.r_floor','ca.url')
            //     -> where('de.eui' ,'=' ,$DevE)
            //     -> first();
                // dd($make);
            if($smoke_area&&$smoke_area['status']==1){
                if($smoke_area){
                    // 拼接建筑信息和位置信息
                    $info['r_type'] = $smoke_area['type'];
                    $info['name'] = $smoke_area['b_name'];
                    $info['lng'] = $smoke_area['b_longitude'];
                    $info['lat'] = $smoke_area['b_latitude'];
                    $info['room'] = $smoke_area['r_name'];
                    $info['r_floor'] = $smoke_area['r_floor'];
                    $info['url'] = $smoke_area['url'];
                    $info['username'] = '';
                    $info['phone'] = '';
                    // $info['cnname'] = '';
                    $userid_rid = DB::table('sa_member_manager_area')
                        -> select('mma_uid')
                        -> where('mma_r_id','=',$smoke_area['r_id'])
                        -> first();
                    // 如果关系表存在
                    if($userid_rid&&$userid_rid['mma_uid']){
                        // 在用户表中查该用户
                        $mma_uid =explode(',',$userid_rid['mma_uid']);
                        $uid = array_pop($mma_uid);
                        $username = DB::table('sa_member')
                            -> select('username','mobile','cnname')
                            -> where('uid',$uid)
                            -> first();
                        $info['username'] = $username['username'];
                        $info['phone'] = $username['mobile'];
                        // $info['cnname'] = $username['cnname'];
                        if(!empty($username['cnname'])){
                            $info['username'] = $username['username'];
                        }
                    }else{
                        // 否则根据建筑ID 查询关系表
                        $userid_bid = DB::table('sa_member_manager_area')
                            -> select('mma_uid')
                            -> where('mma_b_id','=',$smoke_area['b_id'])
                            -> where('mma_r_id','=',0)
                            -> first();
                        // 如果建筑ID存在
                        if($userid_bid&&$userid_bid['mma_uid']){
                            $mma_uid =explode(',',$userid_bid['mma_uid']);
                            $uid = array_pop($mma_uid);
                            $username = DB::table('sa_member')
                                -> select('username','mobile','cnname')
                                -> where('uid',$uid)
                                -> first();
                            $info['username'] = $username['username'];
                            $info['phone'] = $username['mobile'];
                            // $info['cnname'] = $username['cnname'];
                            if(!empty($username['cnname'])){
                                $info['username'] = $username['username'];
                            }
                        }else{
                            // 否则根据区域查关系表
                            $userid_aid = DB::table('sa_member_manager_area')
                                -> select('mma_uid')
                                -> where('mma_a_id','=',$smoke_area['a_id'])
                                -> where('mma_b_id','=',0)
                                -> where('mma_r_id','=',0)
                                -> first();
                            if($userid_aid&&$userid_aid['mma_uid']){
                                $mma_uid =explode(',',$userid_aid['mma_uid']);
                                $uid = array_pop($mma_uid);
                                $username = DB::table('sa_member')
                                    -> select('username','mobile','cnname')
                                    -> where('uid',$uid)
                                    -> first();
                                $info['username'] = $username['username'];
                                $info['phone'] = $username['mobile'];
                                // $info['cnname'] = $username['cnname'];
                                if(!empty($username['cnname'])){
                                    $info['username'] = $username['username'];
                                }
                            }
                        }
                    }
                    //dd($info);
                    if($info){
                        echo json_encode($info);
                    }else{
                        echo '';
                    }
                }else{
                    echo '';
                }
            }    
        }
    }
}
